package com.zhb.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhb.lkd.base.PageResponse;
import com.zhb.lkd.exception.BusinessException;
import com.zhb.lkd.mapper.SkuClassMapper;
import com.zhb.lkd.pojos.entity.Sku;
import com.zhb.lkd.mapper.SkuMapper;
import com.zhb.lkd.pojos.entity.SkuClass;
import com.zhb.lkd.pojos.vo.SkuVo;
import com.zhb.lkd.service.ISkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author haibin
 * @since 2024-08-18
 */
@Service
@Transactional
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements ISkuService {
    @Resource
    private SkuClassMapper skuClassMapper;

    /**
     * 商品搜索
     *
     * @param pageIndex
     * @param pageSize
     * @param skuName
     * @return
     */
    @Override
    public PageResponse search(Integer pageIndex, Integer pageSize, String skuName) {
        //1.检查参数
        //2.分页查询
        Page<Sku> page = lambdaQuery()
                .like(StrUtil.isNotBlank(skuName), Sku::getSkuName, skuName)
                .page(new Page<>(pageIndex, pageSize));
        List<SkuVo> skuVos = page.getRecords().stream().map(sku -> {
            SkuVo skuVo = BeanUtil.copyProperties(sku, SkuVo.class);
            SkuClass skuClass = skuClassMapper.selectById(sku.getClassId());
            if (skuClass != null) {
                skuVo.setSkuClass(skuClass);
            }
            return skuVo;
        }).collect(Collectors.toList());
        return new PageResponse(page,skuVos);
    }

    /**
     * 新增商品
     * @param sku
     */
    @Override
    public void create(Sku sku) {
        //1.检查参数
        if (StrUtil.isBlank(sku.getSkuName())){
            throw new BusinessException(500,"商品名称不能为空");
        }
        //2.保存
        save(sku);
    }
}
